<template>
  <div class="dc-container">
    <el-dialog v-model="visible" width="60%"
      :fullscreen="false" :title="title" :close-on-click-modal="false"
      @open="onDialogOpen" @close="onDialogClose">
      <el-tabs v-model="tabName" type="border-card" tab-position="top">
        <el-tab-pane label="字典类型" name="editForm">
          <!-- 主表编辑表单 -->
          <el-form ref="editForm" :model="form" :rules="rules" label-width="100px" :disabled="mode == 'view'">
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item prop="code" label="编号">
                  <el-input v-model="form.code" :maxLength="64" placeholder="请输入编号" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="name" label="名称">
                  <el-input v-model="form.name" :maxLength="128" placeholder="请输入名称" clearable></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item prop="isSystem" label="是否系统级">
                  <el-select v-model="form.isSystem" placeholder="请选择是否系统级" clearable style="width: 100%">
                    <el-option label="是" value="1"></el-option>
                    <el-option label="否" value="0"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="remarks" label="备注信息">
                  <el-input v-model="form.remarks" :maxLength="255" placeholder="请输入备注信息" clearable></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>

        <!-- 从表编辑表单 - 字典项 -->
        <el-tab-pane label="字典项" name="dictItemTable">
          <!-- 从表操作按钮 -->
          <el-row v-if="mode != 'view'" :gutter="0" justify="end" align="top">
            <el-button type="primary" icon="Plus" plain @click="form.dictItemList.push({})"></el-button>
          </el-row>
          <!-- 从表编辑表格 -->
          <el-row>
            <vxe-table :id="'dictItemTableRef_' + $route.meta.routerId"  ref="dictItemTableRef" :data="form.dictItemList" style="width: 100%" height="340px"
              :edit-rules="dictItemRules" :edit-config="{trigger: 'click', mode: 'row', showStatus: true}">
              <!-- 从表字段列 -->
              <vxe-column field="name" title="名称" min-width="120px" align="left" show-overflow :edit-render="{ autofocus: '.el-input__inner' }">
                <template #edit="{ row }">
                  <el-input v-model="row.name" :maxLength="128" placeholder="请输入名称" clearable autocomplete="new-password" :disabled="mode == 'view'"></el-input>
                </template>
              </vxe-column>
              <vxe-column field="value" title="字典项值" min-width="120px" align="left" show-overflow :edit-render="{ autofocus: '.el-input__inner' }">
                <template #edit="{ row }">
                  <el-input v-model="row.value" :maxLength="128" placeholder="请输入字典项值" clearable autocomplete="new-password" :disabled="mode == 'view'"></el-input>
                </template>
              </vxe-column>
              <vxe-column field="remarks" title="备注信息" min-width="120px" align="left" show-overflow :edit-render="{ autofocus: '.el-input__inner' }">
                <template #edit="{ row }">
                  <el-input v-model="row.remarks" :maxLength="255" placeholder="请输入备注信息" clearable autocomplete="new-password" :disabled="mode == 'view'"></el-input>
                </template>
              </vxe-column>
              <!-- 操作列 -->
              <vxe-column title="操作" width="80px" fixed="right" v-if="mode != 'view'">
                <template #default="scope">
                  <OperationIcon @click="form.dictItemList.splice(scope.rowIndex, 1)" type="danger" content="删除" icon-name="Delete"></OperationIcon>
                </template>
              </vxe-column>
            </vxe-table>
          </el-row>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onSubmit" type="primary" v-show="mode != 'view'">保存</el-button>
          <el-button @click="onDialogClose" v-if="mode != 'view'">取消</el-button>
          <el-button @click="onDialogClose" v-if="mode == 'view'">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { getDictTypeById, saveDictType } from '@/api/sys/dictType'
import BaseUI from '@/views/components/baseUI'
import OperationIcon from '@/components/OperationIcon'

export default {
  extends: BaseUI,
  name: 'dictType-form',
  components: {
    OperationIcon
  },
  data() {
    return {
      // 操作模式 view/edit/add
      mode: 'add',
      form: this.initForm(),
      // 对话框属性变量
      visible: false,
      title: '字典类型',
      tabName: 'editForm',
      // 主表表单验证规则
      rules: {
        code: [{ required: true, message: '编号不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        isSystem: [{ required: true, message: '是否系统级不能为空', trigger: 'blur' }]
      },
      // 从表验证规则
      dictItemRules: {
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        value: [{ required: true, message: '字典项值不能为空', trigger: 'blur' }]
      }
    }
  },
  props: {
    // 权限
    permission: {
      type: Object
    }
  },
  methods: {
    // 必须实现的方法
    async onSubmit() {
      let validFlag = true

      // 验证从表表单
      const valid = await this.$refs['dictItemTableRef'].validate(true)
      if (valid) {
        this.tabName = 'dictItemTable'
        validFlag = false
        return false
      }

      // 验证主表表单
      await this.$refs.editForm.validate((valid) => {
        if (!valid) {
          this.tabName = 'editForm'
          validFlag = false
          return false
        }
      })

      if (validFlag) {
        this.doSave()
      }
    },
    // 必须实现的方法
    doSave() {
      this.setLoad()
      saveDictType(this.form)
        .then((responseData) => {
          if (responseData.code == 100) {
            this.visible = false
            this.showMessage({
              type: 'success',
              msg: '保存成功'
            })
            this.$emit('save-finished')
          } else {
            this.showMessage(responseData)
          }
          this.resetLoad()
        })
        .catch((error) => {
          this.outputError(error)
        })
    },
    // 必须实现的方法
    getFormById(id) {
      this.setLoad()
      return new Promise((resolve) => {
        getDictTypeById(id)
          .then((responseData) => {
            let form = {}
            if (responseData.code == 100) {
              form = responseData.data
            } else {
              this.showMessage(responseData)
            }
            this.resetLoad()
            resolve(form)
          })
          .catch((error) => {
            this.outputError(error)
          })
      })
    },
    // 必须实现的方法
    onDialogClose() {
      this.visible = false
    },
    // 必须实现的方法
    onDialogOpen() {
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate()
      })
    },
    // 必须实现的方法 - 初始化表单数据
    initForm() {
      return {
        id: null,
        code: '',
        name: '',
        isSystem: '0', // 默认不是系统级
        remarks: '',
        dictItemList: []
      }
    },
    // 必须实现的方法 - 打开查看模式
    async openView(id) {
      this.mode = 'view'
      this.title = `查看字典类型`
      this.form = {
        ...this.initForm(),
        ...(await this.getFormById(id))
      }
      this.visible = true
    },
    // 必须实现的方法 - 打开编辑模式
    async openEdit(id) {
      this.mode = 'edit'
      this.title = `修改字典类型`
      this.form = {
        ...this.initForm(),
        ...(await this.getFormById(id))
      }
      this.visible = true
    },
    // 必须实现的方法 - 打开新增模式
    openAdd(parent) {
      this.mode = 'add'
      this.title = `添加字典类型`
      this.form = this.initForm()
      this.visible = true
    },
    // 必须实现的方法 - 打开复制模式
    async openCopy(id) {
      this.mode = 'add'
      this.title = `添加字典类型`
      this.form = {
        ...this.initForm(),
        ...(await this.getFormById(id))
      }
      this.form.id = null // 把id设置为空，添加一个新的

      // 清空从表ID
      for (var i = 0; i < this.form.dictItemList.length; i++) {
        this.form.dictItemList[i].id = null
      }

      this.visible = true
    }
  }
}
</script> 